@echo off
:: Script to download and install the latest version of CMake on Windows

:: Check if running as administrator
net session >nul 2>&1
if %errorLevel% == 0 (
    echo Running as administrator...
) else (
    echo Please run this script as administrator!
    pause
    exit /b
)

:: Set the path to save the installer
set DOWNLOAD_PATH=%USERPROFILE%\Downloads\cmake-installer.msi

:: Fetch the latest release information from GitHub releases page
echo Fetching the latest CMake release information from GitHub...
for /f "delims=" %%i in ('powershell -Command "(Invoke-WebRequest -Uri 'https://api.github.com/repos/Kitware/CMake/releases/latest' -UseBasicParsing | ConvertFrom-Json).assets | Where-Object { $_.name -match 'windows-x86_64\.msi' } | Select-Object -ExpandProperty browser_download_url"') do (
    set CMAKE_URL=%%i
)

:: Check if the CMake URL was found
if "%CMAKE_URL%"=="" (
    echo Failed to find the CMake download URL!
    pause
    exit /b
)

:: Output the CMake download URL for debugging
echo Found CMake download URL: %CMAKE_URL%

:: Check if the file already exists
if exist "%DOWNLOAD_PATH%" (
    echo CMake installer already exists at %DOWNLOAD_PATH%. Skipping download...
    goto INSTALL
)

:: Download the CMake installer using PowerShell
echo Downloading CMake installer...
powershell -Command "Invoke-WebRequest -Uri '%CMAKE_URL%' -OutFile '%DOWNLOAD_PATH%'"

:: Check if the download was successful
if not exist "%DOWNLOAD_PATH%" (
    echo Failed to download CMake installer!
    pause
    exit /b
)

:INSTALL
:: Set the full path to msiexec.exe to avoid path issues
set MSIEXEC_PATH=%SystemRoot%\System32\msiexec.exe

:: Debugging: Check if msiexec.exe exists
if not exist "%MSIEXEC_PATH%" (
    echo msiexec.exe not found! Checking %MSIEXEC_PATH%...
    pause
    exit /b
)

echo Installing CMake MSI installer...

:: Install CMake with a normal installation dialog
start /wait "%MSIEXEC_PATH%" /i "%DOWNLOAD_PATH%"

:: Set the CMake installation directory
set INSTALL_DIR="C:\CMake"

:: Check if the installation was successful
if not exist "%INSTALL_DIR%" (
    echo CMake installation failed!
    pause
    exit /b
)

:: Add CMake to the system environment variables
echo Adding CMake to system environment variables...
set CMAKE_BIN_PATH=%INSTALL_DIR%\bin
setx PATH "%PATH%;%CMAKE_BIN_PATH%" /M

:: Verify if the PATH was updated successfully
echo Verifying PATH update...
powershell -Command "[System.Environment]::GetEnvironmentVariable('PATH', 'Machine')" | findstr /i "CMake" >nul
if %errorLevel% neq 0 (
    echo Failed to add CMake to the system PATH!
    pause
    exit /b
)

:: Clean up the installer
echo Cleaning up the installer...
del "%DOWNLOAD_PATH%"

echo CMake installation and configuration completed!
pause











